<route lang="json5">
{
  meta: {
    auth: true,
    label: '首页统计面板',
  },
}
</route>

<style lang="scss" scoped></style>

<template>
  <use-mouse-selection
    item-query=".stat-card"
    class="select-none h-full w-full"
    :handle-select="
      (node, index) => {
        boardDict[index].selected = !boardDict[index].selected
      }
    "
  >
    <DefineGap v-slot="{ value }">
      <template v-if="value > 0">
        <span class="mr-2">+{{ value }}</span>
        <Icon class="text-green-500" icon="iconoir:stat-up" />
      </template>
      <template v-else-if="value < 0">
        <span class="mr-2">{{ value }}</span>
        <Icon class="text-red-500" icon="iconoir:stat-down" />
      </template>
      <span v-else class="mr-2">steady</span>
    </DefineGap>

    <vue-draggable-next v-model="boardDict" class="flex flex-wrap gap-2 p-4" ghost-class="opacity-50">
      <div
        v-for="item in boardDict"
        :key="item.name"
        @mousedown.stop
        @click="item.selected = !item.selected"
        :class="[
          'stat-card',
          'select-none rounded px-4 py-2 border border-blue-100 active:cursor-move min-w-[9rem]',
          {
            ' ring-2': item.selected,
          },
        ]"
      >
        <p class="flex items-center text-sm">
          <span class="mr-2">{{ item.name }}</span>
          <a-tooltip v-if="item.tooltip" :content="item.tooltip">
            <Icon class="text-xs" icon="simple-line-icons:exclamation" />
          </a-tooltip>
        </p>
        <count-to
          decimal="."
          separator=","
          :decimals="0"
          class="text-3xl font-mono"
          :startVal="prevStatValue[item.key] || 0"
          :endVal="statValue[item.key] || 0"
          :duration="1000"
        />
        <span class="ml-1 text-sm">{{ item.unit }}</span>

        <div class="flex items-center">
          <RenderGap :value="statValue[item.key] - prevStatValue[item.key]" />
        </div>
      </div>
    </vue-draggable-next>

    <a-button @click="handleGetData">随机刷新数据</a-button>

    <div class="text-red-500 mt-8">
      <p>已支持：</p>
      <p>·拖拽排序</p>
      <p>·数据缓存</p>
      <p>·拖拽框选</p>
    </div>
  </use-mouse-selection>
</template>

<script lang="ts" setup>
import { CountTo } from 'vue3-count-to'
import { VueDraggableNext } from 'vue-draggable-next'

const { handleGetData } = useStat()
const { boardDict, statValue } = storeToRefs(useStat())

const { history } = useRefHistory(statValue, { capacity: 1 }) // 存储一条历史记
const prevStatValue = computed(() => history.value?.[1]?.snapshot || {}) // 取出上次记录
const [DefineGap, RenderGap] = createReusableTemplate<{ value: number }>()
</script>
